import logging
import datetime
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from rest_framework.authentication import TokenAuthentication
from rest_framework.views import APIView
from backend.common.api_response import JsonResponse
from backend.models import Lyzd_Interface_Action, Lyzd_Interface_Action_Detail, Lyzd_InterfaceCase_Action
from backend.serializers import Lyzd_Interface_ActionSerializer, Lyzd_Interface_Action_DetailSerializer, \
    AutomationTestLatelyTenTimeSerializer, Lyzd_InterfaceCase_ActionSerializer

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。
"""
获取运行结果
"""

class getRunResult(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))
        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")
        try:
            project_id = request.GET.get("getProjectFirstID")
            if project_id is None:
                return JsonResponse(code="999985", msg="请选择所属项目")

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="请选择所属项目")
        try:
            start_time = request.GET.get("start_time")
            end_time = request.GET.get("end_time")
            # if start_time is None:
            #     return JsonResponse(code="999985", msg="请选则时间范围")
            # if end_time is None:
            #     return JsonResponse(code="999985", msg="请选则时间范围")
            if start_time == ' 0:0':
                return JsonResponse(code="999985", msg="请选则时间范围")
            if end_time == ' 23:59':
                return JsonResponse(code="999985", msg="请选则时间范围")

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="请选则时间范围")
        """
        从现在开始必须查询项目id、时间起始值和页码
        
        1接口名称
        2执行结果
        list转datetime.datetime  ======   print(datetime.datetime(*datetime_list))
        """
        request.GET.get("result")
        result = request.GET.get("result")
        interface_pici = request.GET.get("pici")
        """
        前端传到后台的值是年月日时分，且01展示1，没有秒，需要构建[2021, 1, 4, 14, 46, 0]
        """
        """时间处理开始================"""
        start_time_str = start_time + ":0"
        """格式化字符串将-和: 转换成空格"""
        start_time_str = start_time_str.replace('-', ' ')  # -转空格
        start_time_str = start_time_str.replace(':', ' ')  #:转空格
        start_time_list = start_time_str.split()  # str写进list
        start_time_list = list(map(int, start_time_list))  # list内全是str，转list内全是int
        s_time = datetime.datetime(*start_time_list)  # 开始时间转换成数据库能查询的参数

        end_time_str = end_time + ":0"
        """格式化字符串将-和: 转换成空格"""
        end_time_str = end_time_str.replace('-', ' ')
        end_time_str = end_time_str.replace(':', ' ')
        end_time_list = end_time_str.split()
        end_time_list = list(map(int, end_time_list))  # 日期xinng
        e_time = datetime.datetime(*end_time_list)
        """时间处理结束================"""

        if result is None:  # 查询全部结果，则不需要此判断条件 create_time in(start_time))  (time__range=(start_date, end_date))
            if interface_pici is None:
                if project_id is None or project_id == '0':
                    obi = Lyzd_Interface_Action.objects.filter(
                        create_time__range=(s_time, e_time)).order_by("-id")
                else:
                    obi = Lyzd_Interface_Action.objects.filter(project=project_id,
                                                               create_time__range=(s_time, e_time)).order_by("-id")


            else:
                if project_id is None or project_id == '0':
                    obi = Lyzd_Interface_Action.objects.filter(
                        interface_pici__contains=interface_pici,
                        create_time__range=(s_time, e_time)).order_by("-id")
                else:
                    obi = Lyzd_Interface_Action.objects.filter(project=project_id,
                                                               interface_pici__contains=interface_pici,
                                                               create_time__range=(s_time, e_time)).order_by("-id")



        else:
            if interface_pici is None:
                if project_id is None or project_id == '0':
                    obi = Lyzd_Interface_Action.objects.filter(interface_res=result,
                                                               create_time__range=(s_time, e_time)).order_by("-id")
                else:
                    obi = Lyzd_Interface_Action.objects.filter(project=project_id, interface_res=result,
                                                               create_time__range=(s_time, e_time)).order_by("-id")

            else:
                if project_id is None or project_id == '0':

                    obi = Lyzd_Interface_Action.objects.filter(interface_res=result,
                                                               interface_pici__contains=interface_pici,
                                                               create_time__range=(s_time, e_time)).order_by("-id")
                else:
                    obi = Lyzd_Interface_Action.objects.filter(project=project_id, interface_res=result,
                                                               interface_pici__contains=interface_pici,
                                                               create_time__range=(s_time, e_time)).order_by("-id")

        # 分页
        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数
        try:
            obm = paginator.page(page)
        except PageNotAnInteger:
            obm = paginator.page(1)
        except EmptyPage:
            obm = paginator.page(paginator.num_pages)
        serialize = Lyzd_Interface_ActionSerializer(obm, many=True)

        return JsonResponse(data={"data": serialize.data, "page": page, "total": total}, code="999999", msg="成功")


class getRunResultByPici(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):

        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))
        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")

        interface_pici = request.GET.get("pici")
        obi = Lyzd_Interface_Action.objects.filter(
            interface_pici__contains=interface_pici,
        ).order_by("-id")

        serialize = Lyzd_Interface_ActionSerializer(obi, many=True)
        print(serialize.data)
        return JsonResponse(data={"data": serialize.data}, code="999999", msg="成功")


"""获取执行结果详情"""


class getResultDetail(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))
        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")
        """查询条件"""
        # 必传参数
        pici = request.GET.get("pici")
        # 非必传
        interface_name = request.GET.get("interface_name")
        interface_case_name = request.GET.get("interface_case_name")
        if not pici:
            return JsonResponse(code="999996", msg="参数有误！")
        # key_id = Lyzd_Interface_Action.objects.get(interface_pici=pici)
        """获取主表的case_type"""
        # add_id = Lyzd_Interface.objects.filter(interface_name_zh=data["interface_name_zh"])

        # id_new = add_id[0].id
        Lyzd_Interface_Action.objects.filter(interface_pici=pici)
        print("EOF")
        print(Lyzd_Interface_Action)
        casetype = Lyzd_Interface_Action.case_type
        print(str(casetype))
        print(222222)

        obi = Lyzd_InterfaceCase_Action.objects.filter(interface_pici=pici).extra(select={
            'case_type_name': 'select  lyzd_interface_action.case_type   from lyzd_interface_action  where  interface_pici=%s' % pici

        }).order_by("-id")

        if interface_case_name:
            if interface_name:  # 同时存在
                obi = Lyzd_InterfaceCase_Action.objects.filter(
                    interface_pici=pici,
                    interface_case_name__contains=interface_name,
                    interface_name__contains=interface_case_name).extra(select={
                    'case_type_name': 'select distinct lyzd_interface_action.case_type   from lyzd_interface_action   where  interface_pici=%s' % pici

                }).order_by("-id")
            else:  # 接口名不存在、用例存在
                obi = Lyzd_InterfaceCase_Action.objects.filter(
                    interface_pici=pici,
                    interface_name__contains=interface_case_name).extra(select={
                    'case_type_name': 'select distinct lyzd_interface_action.case_type   from lyzd_interface_action   where  interface_pici=%s' % pici

                }).order_by("-id")
        else:  # 用例不存在
            if interface_name:  # interface_name 存在
                obi = Lyzd_InterfaceCase_Action.objects.filter(
                    interface_pici=pici, interface_name__contains=interface_name).extra(select={
                    'case_type_name': 'select distinct lyzd_interface_action.case_type   from lyzd_interface_action  where   interface_pici=%s' % pici

                }).order_by("-id")
            else:  # interface_name 不存在
                obi = Lyzd_InterfaceCase_Action.objects.filter(interface_pici=pici).extra(select={
                    'case_type_name': 'select distinct lyzd_interface_action.case_type   from lyzd_interface_action   where  interface_pici=%s' % pici

                }).order_by("-id")
        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数
        try:
            obm = paginator.page(page)
        except PageNotAnInteger:
            obm = paginator.page(1)
        except EmptyPage:
            obm = paginator.page(paginator.num_pages)
        serialize = Lyzd_InterfaceCase_ActionSerializer(obm, many=True)
        print(serialize.data)
        return JsonResponse(data={"data": serialize.data,
                                  "page": page,
                                  "total": total}, code="999999", msg="成功")


"""详情弹窗"""


class getResultDetailByID(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        print(33333333)
        """查询条件"""
        # 必传参数
        cid = request.GET.get("cid")
        print("444444444")
        print(cid)
        if not cid:
            return JsonResponse(code="999996", msg="参数有11111误！")
        print(5555)
        # key_id = Lyzd_Interface_Action.objects.get(interface_pici=pici)
        obi = Lyzd_Interface_Action_Detail.objects.filter(interfacecase_action=cid).order_by("-id")

        # obi = Lyzd_InterfaceCase_Action.objects.filter(interface_pici=pici).order_by("-id")

        serialize = Lyzd_Interface_Action_DetailSerializer(obi, many=True)
        print(serialize.data)
        return JsonResponse(data={"data": serialize.data, }, code="999999", msg="成功")
